#include <func.h>

typedef struct 
{
    int file_len;
    char* file_name[50];
} File;


int main(void)
{
    char file_name[8] = "udp.txt";
    int sock_fd = socket(AF_INET, SOCK_STREAM, 0);

    struct sockaddr_in addr;
    addr.sin_family = AF_INET;
    addr.sin_port = htons(atoi("8080"));
    addr.sin_addr.s_addr = inet_addr("127.0.0.1");

    connect(sock_fd, (struct sockaddr*)&addr, sizeof(addr));
    fprintf(stderr, "连接成功\n");


    File file;
    while(1)
    {
        memset(&file, 0, sizeof(file));

        char buff[50] = {0};
        fprintf(stderr, "请输入文件名: ");
        int count = read(STDIN_FILENO, buff, sizeof(buff));
        memcpy(file.file_name, buff, count - 1);
        send(sock_fd, &file, sizeof(file), 0);


        recv(sock_fd, &file, sizeof(file), 0);
        printf("file_len = %d\n", file.file_len);
        if(file.file_len == 0)
        {
            fprintf(stderr, "没有这个文件\n");
            continue;
        }

        int file_fd = open(file.file_name, O_RDWR | O_CREAT | O_TRUNC, 0666);

        char buf[128] = {0};
        count = recv(sock_fd, buf, file.file_len, 0);
        printf("buf = %s\n", buf);
        write(file_fd, buf, count);
        fprintf(stderr, "%s: 传输完成\n", file.file_name);
    }

    close(sock_fd);
    return 0;
}
